﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Communication.Channel;
using Communication.Message.FpgaUpdate;
using Vosc.Logging;

namespace Vosc
{
	// Token: 0x0200000B RID: 11
	public partial class FpgaUpdateForm : Form
	{
		// Token: 0x0600005A RID: 90 RVA: 0x00007782 File Offset: 0x00005982
		public FpgaUpdateForm()
		{
			this.InitializeComponent();
		}

		// Token: 0x0600005B RID: 91 RVA: 0x00007790 File Offset: 0x00005990
		public FpgaUpdateForm(Channel channel, FlashUpdateType updateTarget, string updateFile) : this()
		{
			this.channel = channel;
			this.updateTarget = updateTarget;
			this.updateFile = updateFile;
			this.runStatus = FpgaUpdateForm.RunStatus.Running;
			this.Text = string.Format("{0} 正在升级...", Enum.GetName(typeof(FlashUpdateType), updateTarget));
			this.buttonOK.Enabled = false;
		}

		// Token: 0x0600005C RID: 92 RVA: 0x000077F0 File Offset: 0x000059F0
		private void FpgaUpdateForm_Shown(object sender, EventArgs e)
		{
			Delegate method = new EventHandler(this.Update);
			object[] args = new object[2];
			base.BeginInvoke(method, args);
		}

		// Token: 0x0600005D RID: 93 RVA: 0x00007818 File Offset: 0x00005A18
		private void Update(object obj, EventArgs arg)
		{
			try
			{
				FlashUpdateChannelMessage.totalSendByte = 0L;
				FlashUpdateChannelMessage.totalReceiveByte = 0L;
				this.labelTip.Text = "正在请求升级...";
				Application.DoEvents();
				int i;
				for (i = 0; i < 3; i++)
				{
					NormalMessage normalMessage = new NormalMessage((byte)this.updateTarget, 1, null, 0, 0, 1000, 1000, 500);
					this.channel.WriteSync(normalMessage);
					if (normalMessage.IsSuccess() && normalMessage.ErrorCode == FlashUpdateErrorCode.SUCCESS)
					{
						this.WriteLog(normalMessage);
						break;
					}
					this.WriteLog(normalMessage);
				}
				if (i >= 3)
				{
					this.labelTip.Text = "请求升级失败";
				}
				else
				{
					this.labelTip.Text = "正在握手...";
					Application.DoEvents();
					for (i = 0; i < 3; i++)
					{
						SendHandshakeMessage sendHandshakeMessage = new SendHandshakeMessage((byte)this.updateTarget, 2, 1000, 1000, 500);
						this.channel.WriteSync(sendHandshakeMessage);
						if (sendHandshakeMessage.IsSuccess() && sendHandshakeMessage.ErrorCode == FlashUpdateErrorCode.SUCCESS)
						{
							this.WriteLog(sendHandshakeMessage);
							break;
						}
						this.WriteLog(sendHandshakeMessage);
					}
					if (i >= 3)
					{
						this.labelTip.Text = "握手失败";
					}
					else
					{
						this.labelTip.Text = "正在擦除...";
						this.progressBar.Style = ProgressBarStyle.Marquee;
						Application.DoEvents();
						i = 0;
						while (i < 3)
						{
							NormalMessage normalMessage2 = new NormalMessage((byte)this.updateTarget, 3, null, 0, 0, 30000, 30000, 500);
							this.channel.WriteAsync(normalMessage2);
							while (!normalMessage2.IsDone())
							{
								try
								{
									Application.DoEvents();
									Thread.Sleep(100);
								}
								catch
								{
								}
							}
							if (normalMessage2.IsSuccess())
							{
								if (normalMessage2.ErrorCode != FlashUpdateErrorCode.SUCCESS)
								{
									this.WriteLog(normalMessage2);
									this.progressBar.Style = ProgressBarStyle.Blocks;
									this.labelTip.Text = "擦除失败";
									return;
								}
								this.WriteLog(normalMessage2);
								break;
							}
							else
							{
								this.WriteLog(normalMessage2);
								i++;
							}
						}
						if (i >= 3)
						{
							this.progressBar.Style = ProgressBarStyle.Blocks;
							this.labelTip.Text = "擦除失败";
						}
						else
						{
							this.labelTip.Text = "正在编程...";
							this.progressBar.Style = ProgressBarStyle.Blocks;
							Application.DoEvents();
							byte[] array = null;
							try
							{
								array = File.ReadAllBytes(this.updateFile);
							}
							catch (Exception exception)
							{
								InternalLoggerFactory.Logger.Error("read file error.", exception);
								this.labelTip.Text = "编程失败——文件读取";
								return;
							}
							this.progressBar.Maximum = array.Length;
							this.progressBar.Minimum = 0;
							this.progressBar.Step = 1;
							this.progressBar.Value = 0;
							Application.DoEvents();
							this.sendBlockIdMsg = new SendBlockIndexMessage((byte)this.updateTarget, 0, 1000, 1000, 500);
							this.sendDataMsg = new SendDataMessage((byte)this.updateTarget, 5, array, (array.Length > 256) ? 256 : array.Length, 0, 2000, 2000, 2000);
							this.sendCheckSumMsg = new SendCheckSumMessage((byte)this.updateTarget, 0, 2000, 2000, 500);
							int j = 0;
							short num = 0;
							int num2 = 0;
							while (j < array.Length)
							{
								if (num2 >= 3)
								{
									this.labelTip.Text = "编程失败——发送块重试";
									return;
								}
								int num3 = (array.Length - j > 256) ? 256 : (array.Length - j);
								for (i = 0; i < 3; i++)
								{
									this.sendBlockIdMsg.SetPayload(num);
									this.channel.WriteSync(this.sendBlockIdMsg);
									if (this.sendBlockIdMsg.IsSuccess() && this.sendBlockIdMsg.ErrorCode == FlashUpdateErrorCode.SUCCESS)
									{
										this.WriteLog(this.sendBlockIdMsg);
										break;
									}
									this.WriteLog(this.sendBlockIdMsg);
								}
								if (i >= 3)
								{
									this.labelTip.Text = "编程失败——数据块索引重试";
									return;
								}
								this.sendDataMsg.SetPayload(array, j, num3);
								this.channel.WriteSync(this.sendDataMsg);
								this.WriteLog(this.sendDataMsg);
								Thread.Sleep(50);
								short payload = (short)this.Sum16Check(array, j, num3);
								for (i = 0; i < 3; i++)
								{
									this.sendCheckSumMsg.SetPayload(payload);
									this.channel.WriteSync(this.sendCheckSumMsg);
									if (!this.sendCheckSumMsg.IsSuccess())
									{
										this.WriteLog(this.sendCheckSumMsg);
									}
									else
									{
										if (this.sendCheckSumMsg.ErrorCode == FlashUpdateErrorCode.SUCCESS)
										{
											this.WriteLog(this.sendCheckSumMsg);
											j += num3;
											num += 1;
											this.progressBar.Value = j;
											num2 = 0;
											Application.DoEvents();
											Thread.Sleep(5);
											break;
										}
										if (this.sendCheckSumMsg.ErrorCode == FlashUpdateErrorCode.FAILURE)
										{
											this.WriteLog(this.sendCheckSumMsg);
											this.labelTip.Text = "编程失败——E2PROM写入错误";
											return;
										}
										if (this.sendCheckSumMsg.ErrorCode == FlashUpdateErrorCode.RETRY)
										{
											this.WriteLog(this.sendCheckSumMsg);
											num2++;
											break;
										}
										if (this.sendCheckSumMsg.ErrorCode == FlashUpdateErrorCode.CRCERROR)
										{
											this.WriteLog(this.sendCheckSumMsg);
										}
									}
								}
								if (i >= 3)
								{
									this.labelTip.Text = "编程失败——校验超时重试";
									return;
								}
							}
							this.labelTip.Text = "正在结束升级...";
							Application.DoEvents();
							for (i = 0; i < 3; i++)
							{
								NormalMessage normalMessage3 = new NormalMessage((byte)this.updateTarget, 7, null, 0, 0, 1000, 1000, 500);
								this.channel.WriteSync(normalMessage3);
								if (normalMessage3.IsSuccess())
								{
									this.WriteLog(normalMessage3);
									this.labelTip.Text = "升级成功";
									this.progressBar.Value = this.progressBar.Maximum;
									break;
								}
								this.WriteLog(normalMessage3);
							}
							if (i >= 3)
							{
								this.labelTip.Text = "结束升级失败";
							}
							else
							{
								InternalLoggerFactory.Logger.Error(string.Format("总发送字节数{0}，总接收字节数{1}。", FlashUpdateChannelMessage.totalSendByte.ToString(), FlashUpdateChannelMessage.totalReceiveByte.ToString()));
							}
						}
					}
				}
			}
			catch (Exception exception2)
			{
				this.labelTip.Text = "升级过程中出现未能识别的错误";
				InternalLoggerFactory.Logger.Error("升级过程中出现未能识别的错误", exception2);
			}
			finally
			{
				this.buttonOK.Enabled = true;
				this.runStatus = FpgaUpdateForm.RunStatus.Stoped;
			}
		}

		// Token: 0x0600005E RID: 94 RVA: 0x00007EDC File Offset: 0x000060DC
		private ushort Sum16Check(byte[] data, int offset, int length)
		{
			ushort num = 0;
			for (int i = 0; i < length; i++)
			{
				num += (ushort)data[offset + i];
			}
			return num;
		}

		// Token: 0x0600005F RID: 95 RVA: 0x00007F04 File Offset: 0x00006104
		private void WriteLog(FlashUpdateChannelMessage msg)
		{
			if (msg == null)
			{
				return;
			}
			if (!msg.IsDone())
			{
				return;
			}
			if (msg.GetCause() == null)
			{
				InternalLoggerFactory.Logger.Error(string.Format("write message [{0}] —— desid={1}, funcode={2}, errorcode={3}, sendmsg:{4}, receivemsg:{5}", new object[]
				{
					msg.GetType().FullName,
					msg.DesId.ToString("X2"),
					msg.FunCode.ToString("X2"),
					msg.ErrorCode.ToString(),
					msg.HexDumpSendMessage(),
					msg.HexDumpReceiveMessage()
				}));
				return;
			}
			InternalLoggerFactory.Logger.Error(string.Format("write message [{0}] error —— desid={1}, funcode={2}, errorcode={3}, sendmsg:{4}, receivemsg:{5}", new object[]
			{
				msg.GetType().FullName,
				msg.DesId.ToString("X2"),
				msg.FunCode.ToString("X2"),
				msg.ErrorCode.ToString(),
				msg.HexDumpSendMessage(),
				msg.HexDumpReceiveMessage()
			}), msg.GetCause());
		}

		// Token: 0x06000060 RID: 96 RVA: 0x00008025 File Offset: 0x00006225
		private void buttonOK_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		// Token: 0x06000061 RID: 97 RVA: 0x0000802D File Offset: 0x0000622D
		private void FpgaUpdateForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (this.runStatus == FpgaUpdateForm.RunStatus.Running)
			{
				e.Cancel = true;
			}
		}

		// Token: 0x04000092 RID: 146
		private Channel channel;

		// Token: 0x04000093 RID: 147
		private FlashUpdateType updateTarget;

		// Token: 0x04000094 RID: 148
		private string updateFile;

		// Token: 0x04000095 RID: 149
		private FpgaUpdateForm.RunStatus runStatus;

		// Token: 0x04000096 RID: 150
		private SendBlockIndexMessage sendBlockIdMsg;

		// Token: 0x04000097 RID: 151
		private SendDataMessage sendDataMsg;

		// Token: 0x04000098 RID: 152
		private SendCheckSumMessage sendCheckSumMsg;

		// Token: 0x0200000C RID: 12
		private enum RunStatus
		{
			// Token: 0x0400009A RID: 154
			Running,
			// Token: 0x0400009B RID: 155
			Stoped
		}
	}
}
